
 <!DOCTYPE HTML>
<html lang="ch">
<head>
  <meta charset="UTF-8">
  
    <title>Log4J中的继承关系 | Yuan</title>
    <meta name="viewport" content="width=device-width, initial-scale=1,user-scalable=no">
    
    <meta name="author" content="Luo Yuan">
    

    
    <meta name="description" content="Java代码中可以通过继承关系来扩展类的功能，在Log4J也有类似的机制。">
<meta property="og:type" content="article">
<meta property="og:title" content="Log4J中的继承关系">
<meta property="og:url" content="http://luoyuan800.github.io/2015/07/06/log4j-extend/index.html">
<meta property="og:site_name" content="Yuan">
<meta property="og:description" content="Java代码中可以通过继承关系来扩展类的功能，在Log4J也有类似的机制。">
<meta property="og:locale">
<meta property="article:published_time" content="2015-07-06T01:06:35.000Z">
<meta property="article:modified_time" content="2021-04-22T08:09:16.087Z">
<meta property="article:author" content="Luo Yuan">
<meta name="twitter:card" content="summary">

    
    <link rel="alternative" href="/atom.xml" title="Yuan" type="application/atom+xml">
    
    
    <link rel="icon" href="/img/favicon.ico">
    
    
    <link rel="apple-touch-icon" href="/img/jacman.jpg">
    <link rel="apple-touch-icon-precomposed" href="/img/jacman.jpg">
    
    
<link rel="stylesheet" href="/css/style.css">
<link rel="stylesheet" href="/%02.css">
<link rel="stylesheet" href="/.css">

<meta name="generator" content="Hexo 5.4.0"></head>

  <body>
    <header>
      
<div>
		
			<div id="imglogo">
				<a href="/"><img src="/img/logo.png" alt="Yuan" title="Yuan"/></a>
			</div>
			
			<div id="textlogo">
				<h1 class="site-name"><a href="/" title="Yuan">Yuan</a></h1>
				<h2 class="blog-motto">一点一滴，积累技术</h2>
			</div>
			<div class="navbar"><a class="navbutton navmobile" href="#" title="Menu">
			</a></div>
			<nav class="animated">
				<ul>
					<ul>
					 
						<li><a href="/">Home</a></li>
					
						<li><a href="/archives">Archives</a></li>
					
						<li><a href="/about">About</a></li>
					
					<li>
 					
					<form class="search" action="//google.com/search" method="get" accept-charset="utf-8">
						<label>Search</label>
						<input type="search" id="search" name="q" autocomplete="off" maxlength="20" placeholder="Search" />
						<input type="hidden" name="q" value="site:luoyuan800.github.io">
					</form>
					
					</li>
				</ul>
			</nav>			
</div>
    </header>
    <div id="container">
      <div id="main" class="post" itemscope itemprop="blogPost">
  
	<article itemprop="articleBody"> 
		<header class="article-info clearfix">
  <h1 itemprop="name">
    
      <a href="/2015/07/06/log4j-extend/" title="Log4J中的继承关系" itemprop="url">Log4J中的继承关系</a>
  </h1>
  <p class="article-author">By
       
		<a href="/about" title="Luo Yuan" target="_blank" itemprop="author">Luo Yuan</a>
		
  <p class="article-time">
    <time datetime="2015-07-06T01:06:35.000Z" itemprop="datePublished"> Published 2015-07-06</time>
    
  </p>
</header>
	<div class="article-content">
		
		<div id="toc" class="toc-article">
			<strong class="toc-title">Contents</strong>
		
			<ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#Logger%E7%9A%84%E7%90%86%E8%A7%A3"><span class="toc-number">1.</span> <span class="toc-text">Logger的理解</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E7%BB%A7%E6%89%BF%E5%85%B3%E7%B3%BB"><span class="toc-number">2.</span> <span class="toc-text">继承关系</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E7%88%B6%E7%B1%BB"><span class="toc-number">2.1.</span> <span class="toc-text">父类</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E7%94%A8%E6%88%B7%E8%87%AA%E5%AE%9A%E4%B9%89%E7%9A%84Logger"><span class="toc-number">2.2.</span> <span class="toc-text">用户自定义的Logger</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%BB%A3%E7%A0%81%E4%B8%AD%E7%9B%B4%E6%8E%A5%E5%AE%9A%E4%B9%89%E5%AD%90%E7%B1%BB"><span class="toc-number">2.3.</span> <span class="toc-text">代码中直接定义子类</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E7%BB%A7%E6%89%BF%E5%85%B3%E7%B3%BB%E7%9A%84%E7%94%A8%E5%A4%84"><span class="toc-number">3.</span> <span class="toc-text">继承关系的用处</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#RootLogger"><span class="toc-number">4.</span> <span class="toc-text">RootLogger</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E7%B1%BB%E5%AE%9E%E4%BE%8BLogger"><span class="toc-number">5.</span> <span class="toc-text">类实例Logger</span></a></li></ol>
		
		</div>
		
		<p>Java代码中可以通过继承关系来扩展类的功能，在Log4J也有类似的机制。</p>
<span id="more"></span>
<h2 id="Logger的理解"><a href="#Logger的理解" class="headerlink" title="Logger的理解"></a>Logger的理解</h2><p>在log4j的使用中，我们是使用<code>Logger.getLogger(name)</code>来获取Logger实例，这里的Logger实例中的名字是有name来指定，这个那么就限定了我们这个logger会使用什么配置。个人的理解是，在log4j中的Logger的实例是根据名字来唯一存在的，一个名字只会存在一个Logger实例。大概可以这样理解，每一个<code>getLogger</code>返回的都是Logger的一个子类，这个子类是静态，每个子类之间是根据名字来区分的。</p>
<h2 id="继承关系"><a href="#继承关系" class="headerlink" title="继承关系"></a>继承关系</h2><h3 id="父类"><a href="#父类" class="headerlink" title="父类"></a>父类</h3><p>既然是继承，那么需要一个父类，Logger是不能直接实例化，而我们可以通过<code>Logger.getRootLogger()</code>方式来取一个名字标识为rootLogger的Logger子类，这个类我们可以看做其他Logger子类的父类，所有的Logger子类都会继承自它。</p>
<h3 id="用户自定义的Logger"><a href="#用户自定义的Logger" class="headerlink" title="用户自定义的Logger"></a>用户自定义的Logger</h3><p>用户自定义的Logger其实际意义就是指定Log4J生成一个指定名称和配置的子类。<br>比如在<em>log4j.properties</em>文件中定义了这么一句</p>
<p> log4j.logger.father=DEBUG, fatherConfig</p>
<p>那么这句话的意思是说定义一个名字为father的logger类，在代码中可以通过<code>Logger.getLogger(“father”);</code> 来获取这个father对应Logger类。那如果我们需要定义一个这个father的子类就应该：</p>
<p> log4j.logger.father.children=INFO,childrenConfig</p>
<p>那么在定义上这个father.children就是一个子类，并且获取方式为：</p>
<p> Logger.getLogger(“father.children”);</p>
<h3 id="代码中直接定义子类"><a href="#代码中直接定义子类" class="headerlink" title="代码中直接定义子类"></a>代码中直接定义子类</h3><p>即使没有在配置文件中显示的写出子类的定义，我们也可以在代码中通过名称来指定logger实例的继承关系：</p>
<p> Logger.getLogger(“father.children.children”);</p>
<p>上面这个语句就使得我们获得了一个继承自father.children的子类father.children.children。</p>
<h2 id="继承关系的用处"><a href="#继承关系的用处" class="headerlink" title="继承关系的用处"></a>继承关系的用处</h2><p>继承的存在对我们最显著的影响是什么呢？</p>
<ul>
<li><p>个人理解是记录到子类上的log也会被父类接收！是的，正常情况，如果使用子类的实例记录一个log信息，那么这个子类的所有父类都会接收到log信息并且记录。如果我们把子类和父类的输出目的地都设置为一样，那么就会发现重复的log信息。<br>比如我们使用以下代码段，并且把<code>father，father.children</code>的输出<em>appender</em>都设置为控制台输出(org.apache.log4j.ConsoleAppender)</p>
<p>Logger logger=Logger.getLogger(“father.children.children”);<br>Logger.info(“这是一个子类的子类log信息”);<br>我们可以在控制台看到3条log信息，分别是由<em>father.children.children、father.children、father</em>上log进行了输出。<br>这里要注意，father的级别被定义为DEBUG，但是我们输出的INFO信息页被father记录了，这个就表明了father接受到子类的log信息之后father的级别限定会被子类的覆盖掉。</p>
</li>
<li><p>其实我个人并不是很理解这个继承关系会给我们带来什么样的好处，或许是某些部分的信息我们希望不仅被自己的log记录，还希望能被其他的log接收到。另外一个好处就是我们使用名字限定的方式在代码中动态获得一个没有在配置文件中指定的logger实例的时候，这个logger会继承那个父类的log配置。</p>
</li>
</ul>
<h2 id="RootLogger"><a href="#RootLogger" class="headerlink" title="RootLogger"></a>RootLogger</h2><p>还有需要注意的一点是，我们经常可以看到别人使用的配置文件里面会定义个：</p>
<p> log4j.rootLogger=DEBUG, append1, append2</p>
<ul>
<li>这里是对最高级的父类进行了<strong>rootLogger</strong>进行了配置限定，如果没有显式定义其他的Logger的话，那么所有代码中获取到的Logger实例都会继承这个配置。</li>
<li>如果同时定义了其他Logger，并且那个Logger有一个继承的子Logger，那么那个子类Logger的继承关系是：children-&gt; father -&gt;rootLogger</li>
<li>可以使用log4j.additivity.LOGNAME=false来屏蔽掉这种关系（注意LOGNAME是LOG的名称不是LOG的配置名）。</li>
</ul>
<h2 id="类实例Logger"><a href="#类实例Logger" class="headerlink" title="类实例Logger"></a>类实例Logger</h2><p>我们经常使用的<code>Logg.getLoggger(class)</code>获取的Logger实例,如果需要配置这些Logger，在配置文件中定义其log规范使用class name来定位。</p>
<p> Log4j.logger.className= class_full_name<br>其含义就是使用class的全限定名来作为logger的名称，这样如果有需要的话我们可以对每个类都定义自己的log规范。<br>当然如果没有在配置文件里面配置这个全限定名字的logger，这个logger会继承rootLogger的配置，如果连rootLogger都没配置，那么log信息是无法被接收的。</p>
  
	</div>
		<footer class="article-footer clearfix">
<div class="article-catetags">

<div class="article-categories">
  <span></span>
  <a class="article-category-link" href="/categories/%E7%BC%96%E7%A8%8B-Java/">编程-Java</a>
</div>


</div>



	<div class="article-share" id="share">
	
	  <div data-url="http://luoyuan800.github.io/2015/07/06/log4j-extend/" data-title="Log4J中的继承关系 | Yuan" data-tsina="" class="share clearfix">
	  </div>
	
	</div>


</footer>

   	       
	</article>
	
<nav class="article-nav clearfix">
 
 <div class="prev" >
 <a href="/2015/07/07/Markdown/" title="Markdown 语法说明">
  <strong>上一篇：</strong><br/>
  <span>
  Markdown 语法说明</span>
</a>
</div>


<div class="next">
<a href="/2015/07/03/gradle/"  title="Gradle使用入门">
 <strong>下一篇：</strong><br/> 
 <span>Gradle使用入门
</span>
</a>
</div>

</nav>

	



</div>  
      <div class="openaside"><a class="navbutton" href="#" title="Show Sidebar"></a></div>

  <div id="toc" class="toc-aside">
  <strong class="toc-title">Contents</strong>
 
 <ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#Logger%E7%9A%84%E7%90%86%E8%A7%A3"><span class="toc-number">1.</span> <span class="toc-text">Logger的理解</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E7%BB%A7%E6%89%BF%E5%85%B3%E7%B3%BB"><span class="toc-number">2.</span> <span class="toc-text">继承关系</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E7%88%B6%E7%B1%BB"><span class="toc-number">2.1.</span> <span class="toc-text">父类</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E7%94%A8%E6%88%B7%E8%87%AA%E5%AE%9A%E4%B9%89%E7%9A%84Logger"><span class="toc-number">2.2.</span> <span class="toc-text">用户自定义的Logger</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%BB%A3%E7%A0%81%E4%B8%AD%E7%9B%B4%E6%8E%A5%E5%AE%9A%E4%B9%89%E5%AD%90%E7%B1%BB"><span class="toc-number">2.3.</span> <span class="toc-text">代码中直接定义子类</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E7%BB%A7%E6%89%BF%E5%85%B3%E7%B3%BB%E7%9A%84%E7%94%A8%E5%A4%84"><span class="toc-number">3.</span> <span class="toc-text">继承关系的用处</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#RootLogger"><span class="toc-number">4.</span> <span class="toc-text">RootLogger</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E7%B1%BB%E5%AE%9E%E4%BE%8BLogger"><span class="toc-number">5.</span> <span class="toc-text">类实例Logger</span></a></li></ol>
 
  </div>

<div id="asidepart">
<div class="closeaside"><a class="closebutton" href="#" title="Hide Sidebar"></a></div>
<aside class="clearfix">

  


  
<div class="categorieslist">
	<p class="asidetitle">Categories</p>
		<ul>
		
		  
			<li><a href="/categories/杂物-医学/" title="杂物-医学">杂物-医学<sup>1</sup></a></li>
		  
		
		  
			<li><a href="/categories/编程-Java/" title="编程-Java">编程-Java<sup>13</sup></a></li>
		  
		
		  
			<li><a href="/categories/编程-Linux-Unix/" title="编程-Linux/Unix">编程-Linux/Unix<sup>4</sup></a></li>
		  
		
		  
			<li><a href="/categories/编程-工具/" title="编程-工具">编程-工具<sup>4</sup></a></li>
		  
		
		  
			<li><a href="/categories/编程-网络协议/" title="编程-网络协议">编程-网络协议<sup>1</sup></a></li>
		  
		
		  
			<li><a href="/categories/网站-开发/" title="网站-开发">网站-开发<sup>2</sup></a></li>
		  
		
		</ul>
</div>


  

  <div class="linkslist">
  <p class="asidetitle">Links</p>
    <ul>
        
          <li>
            
            	<a href="https://coderq.com" target="_blank" title="一个面向程序员交流分享的新一代社区">码农圈</a>
            
          </li>
        
          <li>
            
            	<a href="http://wuchong.me" target="_blank" title="Jark&#39;s Blog">Jark&#39;s Blog</a>
            
          </li>
        
    </ul>
</div>

  


  <div class="rsspart">
	<a href="/atom.xml" target="_blank" title="rss">RSS</a>
</div>

  <div class="weiboshow">
  <p class="asidetitle">Weibo</p>
    <iframe width="100%" height="119" class="share_self"  frameborder="0" scrolling="no" src="http://widget.weibo.com/weiboshow/index.php?language=&width=0&height=119&fansRow=2&ptype=1&speed=0&skin=9&isTitle=1&noborder=1&isWeibo=0&isFans=0&uid=&verifier=&dpc=1"></iframe>
</div>


</aside>
</div>
    </div>
    <footer><div id="footer" >
	
	<div class="line">
		<span></span>
		<div class="author"></div>
	</div>
	
	
	<section class="info">
		<p> Hello ,I&#39;m Luo Yuan in Zhuhai. <br/>
			Here is my place for knowledge accumulation.</p>
	</section>
	 
	<div class="social-font" class="clearfix">
		
		
		
		
		
		
		
		
		
		
	</div>
			
		

		<p class="copyright">
		Powered by <a href="http://hexo.io" target="_blank" title="hexo">hexo</a> and Theme by <a href="https://github.com/wuchong/jacman" target="_blank" title="Jacman">Jacman</a> © 2021 
		
		<a href="/about" target="_blank" title="Luo Yuan">Luo Yuan</a>
		
		
		</p>
</div>
</footer>
    <script src="/js/jquery-2.0.3.min.js"></script>
<script src="/js/jquery.imagesloaded.min.js"></script>
<script src="/js/gallery.js"></script>
<script src="/js/jquery.qrcode-0.12.0.min.js"></script>

<script type="text/javascript">
$(document).ready(function(){ 
  $('.navbar').click(function(){
    $('header nav').toggleClass('shownav');
  });
  var myWidth = 0;
  function getSize(){
    if( typeof( window.innerWidth ) == 'number' ) {
      myWidth = window.innerWidth;
    } else if( document.documentElement && document.documentElement.clientWidth) {
      myWidth = document.documentElement.clientWidth;
    };
  };
  var m = $('#main'),
      a = $('#asidepart'),
      c = $('.closeaside'),
      o = $('.openaside');
  c.click(function(){
    a.addClass('fadeOut').css('display', 'none');
    o.css('display', 'block').addClass('fadeIn');
    m.addClass('moveMain');
  });
  o.click(function(){
    o.css('display', 'none').removeClass('beforeFadeIn');
    a.css('display', 'block').removeClass('fadeOut').addClass('fadeIn');      
    m.removeClass('moveMain');
  });
  $(window).scroll(function(){
    o.css("top",Math.max(80,260-$(this).scrollTop()));
  });
  
  $(window).resize(function(){
    getSize(); 
    if (myWidth >= 1024) {
      $('header nav').removeClass('shownav');
    }else{
      m.removeClass('moveMain');
      a.css('display', 'block').removeClass('fadeOut');
      o.css('display', 'none');
      
      $('#toc.toc-aside').css('display', 'none');
        
    }
  });
});
</script>

<script type="text/javascript">
$(document).ready(function(){ 
  var ai = $('.article-content>iframe'),
      ae = $('.article-content>embed'),
      t  = $('#toc'),
      ta = $('#toc.toc-aside'),
      o  = $('.openaside'),
      c  = $('.closeaside');
  if(ai.length>0){
    ai.wrap('<div class="video-container" />');
  };
  if(ae.length>0){
   ae.wrap('<div class="video-container" />');
  };
  c.click(function(){
    ta.css('display', 'block').addClass('fadeIn');
  });
  o.click(function(){
    ta.css('display', 'none');
  });
  $(window).scroll(function(){
    ta.css("top",Math.max(140,320-$(this).scrollTop()));
  });
});
</script>


<script type="text/javascript">
$(document).ready(function(){ 
  var $this = $('.share'),
      url = $this.attr('data-url'),
      encodedUrl = encodeURIComponent(url),
      title = $this.attr('data-title'),
      tsina = $this.attr('data-tsina'),
      description = $this.attr('description');
  var html = [
  '<div class="hoverqrcode clearfix"></div>',
  '<a class="overlay" id="qrcode"></a>',
  '<a href="https://www.facebook.com/sharer.php?u=' + encodedUrl + '" class="article-share-facebook" target="_blank" title="Facebook"></a>',
  '<a href="https://twitter.com/intent/tweet?url=' + encodedUrl + '" class="article-share-twitter" target="_blank" title="Twitter"></a>',
  '<a href="#qrcode" class="article-share-qrcode" title="微信"></a>',
  '<a href="http://widget.renren.com/dialog/share?resourceUrl=' + encodedUrl + '&srcUrl=' + encodedUrl + '&title=' + title +'" class="article-share-renren" target="_blank" title="人人"></a>',
  '<a href="http://service.weibo.com/share/share.php?title='+title+'&url='+encodedUrl +'&ralateUid='+ tsina +'&searchPic=true&style=number' +'" class="article-share-weibo" target="_blank" title="微博"></a>',
  '<span title="Share to"></span>'
  ].join('');
  $this.append(html);

  $('.hoverqrcode').hide();

  var myWidth = 0;
  function updatehoverqrcode(){
    if( typeof( window.innerWidth ) == 'number' ) {
      myWidth = window.innerWidth;
    } else if( document.documentElement && document.documentElement.clientWidth) {
      myWidth = document.documentElement.clientWidth;
    };
    var qrsize = myWidth > 1024 ? 200:100;
    var options = {render: 'image', size: qrsize, fill: '#2ca6cb', text: url, radius: 0.5, quiet: 1};
    var p = $('.article-share-qrcode').position();
    $('.hoverqrcode').empty().css('width', qrsize).css('height', qrsize)
                          .css('left', p.left-qrsize/2+20).css('top', p.top-qrsize-10)
                          .qrcode(options);
  };
  $(window).resize(function(){
    $('.hoverqrcode').hide();
  });
  $('.article-share-qrcode').click(function(){
    updatehoverqrcode();
    $('.hoverqrcode').toggle();
  });
  $('.article-share-qrcode').hover(function(){}, function(){
      $('.hoverqrcode').hide();
  });
});   
</script>











<link rel="stylesheet" href="/fancybox/jquery.fancybox.css" media="screen" type="text/css">
<script src="/fancybox/jquery.fancybox.pack.js"></script>
<script type="text/javascript">
$(document).ready(function(){ 
  $('.article-content').each(function(i){
    $(this).find('img').each(function(){
      if ($(this).parent().hasClass('fancybox')) return;
      var alt = this.alt;
      if (alt) $(this).after('<span class="caption">' + alt + '</span>');
      $(this).wrap('<a href="' + this.src + '" title="' + alt + '" class="fancybox"></a>');
    });
    $(this).find('.fancybox').each(function(){
      $(this).attr('rel', 'article' + i);
    });
  });
  if($.fancybox){
    $('.fancybox').fancybox();
  }
}); 
</script>



<!-- Analytics Begin -->



<script>
var _hmt = _hmt || [];
(function() {
  var hm = document.createElement("script");
  hm.src = "//hm.baidu.com/hm.js?e6d1f421bbc9962127a50488f9ed37d1";
  var s = document.getElementsByTagName("script")[0]; 
  s.parentNode.insertBefore(hm, s);
})();
</script>



<!-- Analytics End -->

<!-- Totop Begin -->

	<div id="totop">
	<a title="Back to Top"><img src="/img/scrollup.png"/></a>
	</div>
	<script src="/js/totop.js"></script>

<!-- Totop End -->

<!-- MathJax Begin -->
<!-- mathjax config similar to math.stackexchange -->


<!-- MathJax End -->

<!-- Tiny_search Begin -->

<!-- Tiny_search End -->

  </body>
</html>
